import 'package:flutter/material.dart';
import '../models/question.dart';
import 'question_list_screen.dart';
import 'package:provider/provider.dart';
import '../services/wrong_question_provider.dart';
import 'wrong_questions_screen.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('坚果驾考题库'),
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.book),
            tooltip: '错题集',
            onPressed: () {
              _showWrongQuestionsMenu(context);
            },
          ),
        ],
      ),
      body: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                const SizedBox(height: 20),
                const Text(
                  '选择车辆类型',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 40),
                Expanded(
                  child: GridView.count(
                    crossAxisCount: 2,
                    mainAxisSpacing: 16,
                    crossAxisSpacing: 16,
                    children: [
                      _buildVehicleTypeCard(
                        context,
                        '小车',
                        Icons.directions_car,
                        Colors.blue,
                        1,
                      ),
                      _buildVehicleTypeCard(
                        context,
                        '货车',
                        Icons.local_shipping,
                        Colors.orange,
                        2,
                      ),
                      _buildVehicleTypeCard(
                        context,
                        '客车',
                        Icons.directions_bus,
                        Colors.red,
                        3,
                      ),
                      _buildVehicleTypeCard(
                        context,
                        '摩托车',
                        Icons.motorcycle,
                        Colors.amber,
                        4,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 16,
            child: Column(
              children: const [
                Text(
                  '作者：坚果派',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                  textAlign: TextAlign.center,
                ),
                Text(
                  '公众号：nutpi',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                  textAlign: TextAlign.center,
                ),
                Text(
                  '电话：17752170152',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                  textAlign: TextAlign.center,
                ),
                Text(
                  '官网：https://www.nutpi.net/',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVehicleTypeCard(
    BuildContext context,
    String title,
    IconData icon,
    Color color,
    int rank,
  ) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      child: Card(
        elevation: 4,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: InkWell(
          onTap: () {
            _showExamOptions(context, title, icon, color, rank);
          },
          borderRadius: BorderRadius.circular(12),
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [color, color.withOpacity(0.7)],
              ),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(icon, size: 48, color: Colors.white),
                const SizedBox(height: 12),
                Text(
                  title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _showExamOptions(BuildContext context, String vehicleType, IconData icon,
      Color color, int rank) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) => Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              '选择$vehicleType考试科目',
              style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _buildExamOptionButton(
                  context,
                  '$vehicleType科目一',
                  icon,
                  color,
                  rank,
                  1,
                ),
                _buildExamOptionButton(
                  context,
                  '$vehicleType科目四',
                  icon,
                  color.withOpacity(0.7),
                  rank,
                  2,
                ),
              ],
            ),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  Widget _buildExamOptionButton(
    BuildContext context,
    String title,
    IconData icon,
    Color color,
    int rank,
    int type,
  ) {
    return ElevatedButton(
      onPressed: () {
        Navigator.pop(context); // 关闭底部弹窗
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => QuestionListScreen(
              rank: rank,
              type: type,
              title: title,
            ),
          ),
        );
      },
      style: ElevatedButton.styleFrom(
        backgroundColor: color,
        foregroundColor: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 24),
          const SizedBox(height: 8),
          Text(title),
        ],
      ),
    );
  }

  void _showWrongQuestionsMenu(BuildContext context) {
    // 首先加载错题统计
    final wrongQuestionProvider =
        Provider.of<WrongQuestionProvider>(context, listen: false);

    // 显示加载指示器
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),
      ),
    );

    wrongQuestionProvider.loadStats().then((_) {
      // 关闭加载指示器
      Navigator.pop(context);

      // 显示错题集菜单
      showModalBottomSheet(
        context: context,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        builder: (context) => Consumer<WrongQuestionProvider>(
          builder: (context, provider, child) {
            // 显示错题统计信息用于调试
            print("当前错题统计: ${provider.stats}");

            // 如果没有错题
            if (provider.stats.isEmpty) {
              return Container(
                padding: const EdgeInsets.all(20),
                child: const Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(Icons.check_circle, size: 64, color: Colors.green),
                    SizedBox(height: 16),
                    Text('暂无错题，继续加油！', style: TextStyle(fontSize: 18)),
                    SizedBox(height: 20),
                  ],
                ),
              );
            }

            return Container(
              padding: const EdgeInsets.all(20),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Text(
                    '错题集',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 20),
                  Flexible(
                    child: ListView(
                      shrinkWrap: true,
                      children: [
                        _buildWrongQuestionsTypeButton(context, '小车',
                            Icons.directions_car, Colors.blue, 1),
                        _buildWrongQuestionsTypeButton(context, '货车',
                            Icons.local_shipping, Colors.orange, 2),
                        _buildWrongQuestionsTypeButton(
                            context, '客车', Icons.directions_bus, Colors.red, 3),
                        _buildWrongQuestionsTypeButton(
                            context, '摩托车', Icons.motorcycle, Colors.amber, 4),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      );
    }).catchError((error) {
      // 关闭加载指示器
      Navigator.pop(context);

      // 显示错误提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载错题集失败: $error')),
      );
    });
  }

  Widget _buildWrongQuestionsTypeButton(
    BuildContext context,
    String vehicleType,
    IconData icon,
    Color color,
    int rank,
  ) {
    final wrongQuestionProvider = Provider.of<WrongQuestionProvider>(context);
    final stats = wrongQuestionProvider.stats;

    final subject1Count = stats['${rank}_1'] ?? 0;
    final subject4Count = stats['${rank}_2'] ?? 0;

    if (subject1Count == 0 && subject4Count == 0) {
      return const SizedBox.shrink();
    }

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      color: color.withOpacity(0.1),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(icon, color: color),
                const SizedBox(width: 8),
                Text(
                  vehicleType,
                  style: TextStyle(
                      fontSize: 16, fontWeight: FontWeight.bold, color: color),
                ),
              ],
            ),
            const SizedBox(height: 12),
            if (subject1Count > 0)
              ListTile(
                title: Text('$vehicleType科目一'),
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text('$subject1Count题',
                        style: const TextStyle(color: Colors.red)),
                    const Icon(Icons.arrow_forward_ios, size: 14),
                  ],
                ),
                onTap: () {
                  Navigator.pop(context);
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => WrongQuestionsScreen(
                        rank: rank,
                        type: 1,
                        title: '$vehicleType科目一',
                      ),
                    ),
                  );
                },
              ),
            if (subject4Count > 0)
              ListTile(
                title: Text('$vehicleType科目四'),
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text('$subject4Count题',
                        style: const TextStyle(color: Colors.red)),
                    const Icon(Icons.arrow_forward_ios, size: 14),
                  ],
                ),
                onTap: () {
                  Navigator.pop(context);
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => WrongQuestionsScreen(
                        rank: rank,
                        type: 2,
                        title: '$vehicleType科目四',
                      ),
                    ),
                  );
                },
              ),
          ],
        ),
      ),
    );
  }
}
